package com.zhenxiang.juc.lock.demo01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author : James
 * @Create : 2021-12-20-18:36
 * @Description :  使用Lock 类
 */
public class SaleTicketDemo02 {


    public static void main(String[] args) {

        // 并发需要操作的 共享资源
        Ticket2 ticket = new Ticket2();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    ticket.saleTicket();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程A").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    ticket.saleTicket();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    ticket.saleTicket();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程C").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    ticket.saleTicket();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程D").start();

    }

}

// 线程资源类
class Ticket2{

    // 票量
    private int number =30;

   private Lock lock = new ReentrantLock();
    public  void saleTicket() throws InterruptedException {
        lock.lock();

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "售卖了第" + number-- + "张票, 剩余:" + number + "张");
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
